var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');

var app = express();
var db=require("./db.json");
var fs=require("fs");
var path=require("path");
var fpath=path.join(__dirname,"db.json");
var {promisify}=require("util");
var writeFile=promisify(fs.writeFile);
var multer=require("multer");
var upload=multer({dest:'uploads/'});


// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/users', usersRouter);


//初始化
app.get("/init",function (req,res){
  res.send(db);
});



//创建相册
app.post("/createAlbum",function (req,res){

        var {type}=req.body;
        db.types.push(type);
        db.picture[type]=[];
        writeFile(fpath,JSON.stringify(db));
        res.send();
});

//上传图片
app.post("/upPicture",upload.single('myfiles'),function (req,res){
  // req.file 是 `avatar` 文件的信息
  // req.body 将具有文本域数据，如果存在的话
  const file=req.file;
  const currentAlbum=req.body.type;
          const type=currentAlbum || "default";
          db.picture[type].push({filename:file.filename,createTime:Date.now()});
          writeFile(fpath,JSON.stringify(db));
         res.send(file);
});

//发送图片
app.get("/img/:filename",function (req,res){
  const filename=req.params.filename;
     var result=fs.createReadStream("uploads/"+filename);
      result.pipe(res);
});

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});




// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
